package 算法基础模板.chapter_03;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <pre>{@code
 *   int dfs(int u)
 * {
 *     st[u] = true; // st[u] 表示点u已经被遍历过
 *
 *     for (int i = h[u]; i != -1; i = ne[i])
 *     {
 *         int j = e[i];
 *         if (!st[j]) dfs(j);
 *     }
 * }
 * }</pre>
 * <p>
 * https://www.acwing.com/problem/content/47/
 *
 * @author Summerday
 */
public class DFS {

    List<Integer> line = new ArrayList<>();
    List<List<Integer>> res = new ArrayList<>();
    boolean[] vis;
    int[] nums;

    public List<List<Integer>> permutation (int[] nums) {
        if (nums.length == 0) return res;
        vis = new boolean[nums.length];
        this.nums = nums;
        Arrays.sort(this.nums);
        dfs(0);
        return res;
    }

    void dfs (int u) {
        if (u == nums.length) {
            res.add(new ArrayList<>(line));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i - 1] == nums[i] && !vis[i - 1]) continue;
            if (!vis[i]) {
                vis[i] = true;
                line.add(nums[i]);
                dfs(u + 1);
                line.remove(line.size() - 1);
                vis[i] = false;
            }
        }
    }
}
